"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 进程故障
Case Name   : 数据库运行时，主机注入故障进程异常退出-进程段错误异常退出
Create At   : 2021/8/26
Owner       : @peilinqian
Description :
    1.核对数据库状态
    2.注入进程异常退出-进程段错误异常退出故障
    3.核对数据库状态
    4.恢复环境
    5.主节点执行DML操作
    6.备节点核对一致性
    7.恢复环境
Expect      :
    1.Normal
    2.成功
    3.Unavailable
    4.成功
    5.成功
    6.一致
    7.成功
History     :
    modified by @peilinqian at 2024.2.6:优化调试用例通过并上传
"""

import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node, macro


class ReliabilityProcess(unittest.TestCase):
    nodes = ("PrimaryDbUser", "Standby1DbUser", "Standby2DbUser")

    @RestartDbCluster(*nodes)
    def setUp(self):
        self.log = Logger()
        self.primary_sh = CommonSH(self.nodes[0])
        self.standby_sh = CommonSH(self.nodes[1])
        self.primary_root_node = Node(node="PrimaryRoot")
        self.primary_user_node = Node(node="PrimaryDbUser")
        self.constant = Constant()
        self.com = Common()
        self.table = 't_process_5'

        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.port = Node("PrimaryDbUser").db_port

        self.log.info("查询数据库进程号")
        self.pid = self.com.get_pid(self.primary_user_node, 'bin/gaussdb')
        self.log.info("进程号:" + self.pid)

    def test_main(self):
        try:
            text = "---step1:核对数据库状态;expect:Normal---"
            self.log.info(text)
            db_status = self.primary_sh.getDbClusterStatus("detail")
            self.log.info(db_status)
            self.assertTrue("Degraded" in db_status
                            or "Normal" in db_status, "执行失败" + text)

            text = "---step2:注入进程异常退出-进程段错误异常退出故障;expect:成功---"
            self.log.info(text)
            self.log.info("注入故障")
            inject_cmd = f'rProc_k (typeid, pid) values(5, {self.pid})'
            self.log.info(inject_cmd)
            result = self.com.cfe_inject(self.primary_root_node,
                                         inject_cmd)
            self.log.info(result)
            self.assertIn("", result, "执行失败" + text)
            for i in range(6):
                time.sleep(10)
                result = self.com.cfe_query(self.primary_root_node,
                                            f"rProc_k where pid={self.pid}")
                self.log.info(result)
                if self.constant.no_process_msg in result:
                    break

            text = "---step3:核对数据库状态;expect:Unavailable---"
            self.log.info(text)
            db_status = self.primary_sh.getDbClusterStatus("detail")
            self.log.info(db_status)
            self.assertIn("P Down", db_status, "执行失败" + text)
            self.assertIn("Unavailable", db_status, "执行失败" + text)

        finally:
            text = "---step4:恢复环境;expect:成功---"
            self.log.info(text)
            result = self.primary_sh.executeGsctl("restart",
                                                  "server started")
            self.log.info(result)
            db_status = self.primary_sh.getDbClusterStatus("detail")
            self.log.info(db_status)
            self.assertTrue("Degraded" in db_status
                            or "Normal" in db_status, "执行失败" + text)
            self.assertNotIn("P Down", db_status, "执行失败" + text)

        text = "---step5:主节点执行DML操作;expect:成功---"
        self.log.info(text)
        sql_cmd = f'create table {self.table}(id int);' \
                  f'insert into {self.table} values (generate_series(1,1000));'
        result = self.primary_sh.executDbSql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result, "建表失败")
        self.assertIn(self.constant.insert_success_msg, result, "Insert数据失败")

        text = "检查主备是否同步"
        self.log.info(text)
        time.sleep(10)
        self.log.info("获取节点数量")
        node_num = self.primary_sh.get_node_num()
        res = self.primary_sh.check_location_consistency("primary", node_num)
        self.assertTrue(res, "执行失败" + text)

        text = "---step6:备节点检查数据一致性;expect:成功---"
        self.log.info(text)
        check_sql = f'select count(*) from {self.table};'
        result = self.standby_sh.executDbSql(check_sql)
        self.log.info(result)
        self.assertEqual('1000', result.splitlines()[-2].strip(), '备节点查询数据失败')

    def tearDown(self):
        text = "---step7:恢复环境;expect:成功---"
        self.log.info(text)
        drop = self.primary_sh.executDbSql(
            f'drop table {self.table} cascade;')
        self.log.info(drop)

        result = self.primary_sh.executeGsctl("restart",
                                              "server started")
        self.log.info(result)
        db_status = self.primary_sh.getDbClusterStatus("detail")
        self.log.info(db_status)

        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop, '删除失败')
        self.assertTrue("Degraded" in db_status
                        or "Normal" in db_status, "执行失败" + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
